/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Configuration } from '../config/Configuration'
import { LoggerContext } from '../slf4j/LoggerContext';
import { Filter } from '../config/Filter'
import { Level } from '../Level';
import { FilterEnum } from '../FilterEnum'
import { Match } from '../config/Match'
import { Encoder } from '../encoder/Encoder';
import { FileIO } from '../io/FileIO'
import { PreferencesUtils } from '../util/PreferencesUtils'

export class RollingFileAppender {
    private effectiveLevelInt: number
    private pattern: string
    private className: string
    private filter: Filter
    private maxHistory: number
    private fileNamePattern: string

    start(loggerContext: LoggerContext, configure: Configuration, level: Level, msg: string) {

        for (var i = 0; i < configure.logger.length; i++) {
            if (loggerContext.getLoggerName() == configure.logger[i].name) {
                this.effectiveLevelInt = configure.logger[i].level.getLevelInt()
                this.pattern = configure.appender[i].encoder.pattern.msg
                this.className = configure.appender[i].className
                if (configure.appender[i].filter != null) {
                    this.filter = configure.appender[i].filter
                    this.effectiveLevelInt = configure.appender[i].filter.level.getLevelInt()
                }
                if (configure.appender[i].rollingPolicy != null) {
                    this.maxHistory = configure.appender[i].rollingPolicy.maxHistory
                    this.fileNamePattern = configure.appender[i].rollingPolicy.fileNamePattern
                }
            }
        }
        if (this.effectiveLevelInt > level.getLevelInt()) {
            return
        }
        PreferencesUtils.getData(PreferencesUtils.CURRENT_TIME, PreferencesUtils.CURRENT_TIME, 0, (value) => {
            let dateNow = new Date()
            let timeDiff = dateNow.getTime() - value
            let days = Math.floor(timeDiff / (24 * 3600 * 1000))
            if (days > this.maxHistory) {
                let date = new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDay()
                let file = this.fileNamePattern.replace('%d{yyyy-MM-dd}', date)
                FileIO.create_fileIo(file)
            }
        })
        if (this.filter != null) {
            if (this.filter.className == FilterEnum.LEVEL) {
                if (this.filter.onMatch == Match.ACCEPT && this.filter.onMismatch == Match.DENY) {
                    if (level.getLevelStr() == this.filter.level.getLevelStr()) {
                        FileIO.write_fileIo(Encoder.encoders(loggerContext,this.pattern, level.getLevelStr(), msg))
                    }
                    return
                }
            } else if (this.filter.className == FilterEnum.THRESHOLD) {
                FileIO.write_fileIo(Encoder.encoders(loggerContext,this.pattern, level.getLevelStr(), msg))
            }
        } else {
            FileIO.write_fileIo(Encoder.encoders(loggerContext,this.pattern, level.getLevelStr(), msg))
        }
    }
}